package com.dmsdbj.itoo.graduate.controller;

import com.alibaba.dubbo.config.annotation.Reference;

import com.dmsdbj.itoo.graduate.entity.DictionaryEntity;
import com.dmsdbj.itoo.graduate.entity.PersonalInfoEntity;
import com.dmsdbj.itoo.graduate.entity.ext.PeriodPersonModel;
import com.dmsdbj.itoo.graduate.entity.ext.PersonGradeModel;
import com.dmsdbj.itoo.graduate.entity.ext.PersonInfoModel;
import com.dmsdbj.itoo.graduate.facade.BrowseFacade;
import com.dmsdbj.itoo.graduate.tool.DictionaryTypeCode;
import com.dmsdbj.itoo.graduate.tool.ResultCode;
import com.dmsdbj.itoo.tool.base.entity.TreeEntity;
import com.dmsdbj.itoo.tool.business.ItooResult;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;


/**
 * @author 徐玲博
 * DESCRIPTION: demo展示
 * create: 2017-11-26 16:14:54.
 */
@Api(value = "浏览记录API",tags="浏览记录API")
@RequestMapping("/browse")
@Controller
public class BrowseController {

    //定义打印日志相关
    private static final Logger logger = LoggerFactory.getLogger(BrowseController.class);

    @Reference
    BrowseFacade browseFacade;



    /**
     * 查询全部期数（构建树形结构）--haoguiting-2018-1-30
     * @return 期数list
     */
    @ApiOperation(value="查询全部期数（构建树形结构）",notes="查询全部期数（构建树形结构）")
    @ResponseBody
    @RequestMapping(value = {"/selectAllGrade"}, method = RequestMethod.GET)
    public ItooResult selectAllGrade() {
        try{
            List<DictionaryEntity>  dictionaryEntityList=browseFacade.selectAllGrade(DictionaryTypeCode.GRADE);
            if (dictionaryEntityList != null) {
                return ItooResult.build("0000", "查询全部期数成功！",dictionaryEntityList);
            } else {
                return ItooResult.build("1111", "查询全部期数失败！");
            }
        } catch (Exception e) {
            logger.error("selectAllBrowserByNoticeId 查询全部期数异常", e);
            return ItooResult.build("1111", "查询全部期数异常！");
        }
    }

    /**
     * 修改浏览记录-haoguiting-2017-12-5 14:15:45
     * @param noticeId 通知id
     * @param browsePersonId  浏览人id
     * @return 受影响行
     */
    @ApiOperation(value="修改浏览记录",notes="修改浏览记录")
    @ResponseBody
    @RequestMapping(value = "updateBrowseIsBrowse/{noticeId}/{browsePersonId}", method = RequestMethod.POST)
    public ItooResult updateBrowseIsBrowse(@PathVariable String noticeId, @PathVariable String browsePersonId) {
        int resultCount;
        try {
            resultCount = browseFacade.updateBrowseIsBrowse(noticeId, browsePersonId);
            if (resultCount > 0) {
                return ItooResult.build("0000", "修改浏览记录成功！",resultCount);
            } else {
                return ItooResult.build("1111", "修改浏览记录失败！");
            }
        } catch (Exception e) {
            logger.error("updateBrowse 浏览记录异常", e);
            return ItooResult.build("1111", "修改浏览记录异常！");
        }

    }

    /**
     * 根据通知ID、是否浏览查询浏览人信息-haoguiting-2017-12-5 14:15:45
     * @param noticeId 通知id
     * @param isBrowse 是否浏览
     * @return 浏览人list列表
     */
    @ApiOperation(value="根据通知ID、是否浏览查询浏览人信息",notes="根据通知ID、是否浏览查询浏览人信息")
    @ResponseBody
    @RequestMapping(value = "selectBrowseByNoticeId/{noticeId}/{isBrowse}", method = RequestMethod.GET)
    public ItooResult selectBrowseByNoticeId(@PathVariable String noticeId, @PathVariable String isBrowse) {
        List<PersonInfoModel> personalInfoEntityList;
        try {
            personalInfoEntityList = browseFacade.selectBrowseByNoticeId(noticeId,isBrowse);
            if (personalInfoEntityList != null) {
                return ItooResult.build("0000", "查询浏览记录成功", personalInfoEntityList);
            } else {
                return ItooResult.build("1111", "查询浏览记录失败！");
            }
        } catch (Exception e) {
            logger.error("selectBrowseByNoticeId 浏览记录异常", e);
            return ItooResult.build("1111", "查询浏览记录失败！");
        }


    }

    /**
     * 根据浏览人ID查询未浏览记录-haoguiting-2017-12-5 14:15:45
     * @param browsePersonId 浏览人id
     * @return 受影响行
     */
    @ApiOperation(value="根据浏览人ID查询未浏览记录",notes="根据浏览人ID查询未浏览记录")
    @ResponseBody
    @RequestMapping(value = "selectNoBrowseByBrowsePersonId/{browsePersonId}", method = RequestMethod.POST)
    public ItooResult selectNoBrowseByBrowsePersonId( @PathVariable("browsePersonId") String browsePersonId) {
        int resultCount;
        try {
            resultCount = browseFacade.selectNoBrowseByBrowsePersonId( browsePersonId);
            if (resultCount > 0) {
                return ItooResult.build("0000", "根据浏览人ID查询未浏览记录成功！",resultCount);
            } else {
                return ItooResult.build("1111", "根据浏览人ID查询未浏览记录失败！");
            }
        } catch (Exception e) {
            logger.error("selectNoBrowseByBrowsePersonId 根据浏览人ID查询未浏览记录异常", e);
            return ItooResult.build("1111", "根据浏览人ID查询未浏览记录异常！");
        }

    }


    /**
     * 根据浏览人ID查询已浏览记录-haoguiting-2017-12-5 14:15:45
     * @param browsePersonId 浏览人id
     * @return 受影响行
     */
    @ApiOperation(value="根据浏览人ID查询浏览记录",notes="根据浏览人ID查询浏览记录")
    @ResponseBody
    @RequestMapping(value = "selectBrowsedByBrowsePersonId/{browsePersonId}", method = RequestMethod.POST)
    public ItooResult selectBrowsedByBrowsePersonId( @PathVariable("browsePersonId") String browsePersonId) {
        int resultCount;
        try {
            resultCount = browseFacade.selectBrowsedByBrowsePersonId( browsePersonId);
            if (resultCount > 0) {
                return ItooResult.build("0000", "根据浏览人ID查询已浏览记录成功！",resultCount);
            } else {
                return ItooResult.build("1111", "根据浏览人ID查询已浏览记录失败！");
            }
        } catch (Exception e) {
            logger.error("selectBrowsedByBrowsePersonId 根据浏览人ID查询已浏览记录异常", e);
            return ItooResult.build("1111", "根据浏览人ID查询已浏览记录异常！");
        }

    }

    /**
     * 分页-根据通知ID、是否浏览查询浏览人信息-haoguiting-2018年01月11日
     * @param noticeId  通知Id
     * @param isBrowse  是否浏览
     * @param page 页码
     * @param  pageSize 页大小
     * @return 浏览人list
     */
    @ApiOperation(value="分页查询根据通知ID、是否浏览查询浏览人信息",notes="分页查询根据通知ID、是否浏览查询浏览人信息")
    @ResponseBody
    @RequestMapping(value = "PageSelectBrowseByNoticeId/{noticeId}/{isBrowse}/{page}/{pageSize}", method = RequestMethod.GET)
    public ItooResult PageSelectBrowseByNoticeId(@PathVariable String noticeId, @PathVariable String isBrowse,@PathVariable int page,@PathVariable int pageSize ) {

        try {
            PageInfo<PersonalInfoEntity> manageModelPageInfo = browseFacade.PageSelectBrowseByNoticeId(noticeId,isBrowse,page, pageSize);
            if (CollectionUtils.isEmpty(manageModelPageInfo.getList())) {
                return ItooResult.build(ResultCode.SUCCESS, "无相关条件的查询结果");
            } else {
                return ItooResult.build(ResultCode.SUCCESS, "分页查询根据通知ID、是否浏览查询浏览人信息成功", manageModelPageInfo);
            }
        } catch (Exception e) {
            logger.error("PageSelectBrowseByNoticeId 分页查询根据通知ID、是否浏览查询浏览人信息异常", e);
            return ItooResult.build(ResultCode.FAIL, "分页查询根据通知ID、是否浏览查询浏览人信息失败");
        }


    }

    /**
     * 查询所有期数及对应期数人员 haoguiting -2018年1月14日
     * @return 期数及人员list列表
     */
    @ApiOperation(value="查询浏览人-所有期数及对应期数人员",notes="查询浏览人-所有期数及对应期数人员")
    @ResponseBody
    @RequestMapping(value = "findPeriodPersonModels/", method = RequestMethod.GET)
    public ItooResult findPeriodPersonModels() {
        List<PeriodPersonModel> periodPersonModelList;
        try {
            periodPersonModelList = browseFacade.findPeriodPersonModels();
            if (periodPersonModelList != null) {
                return ItooResult.build("0000", "查询浏览人成功", periodPersonModelList);
            } else {
                return ItooResult.build("1111", "查询浏览人失败！");
            }
        } catch (Exception e) {
            logger.error("findPeriodPersonModels 查询浏览人异常", e);
            return ItooResult.build("1111", "查询浏览人失败！");
        }
    }

    /**
     * 根据通知ID查询全部浏览人-haoguiting-2017-12-5 14:15:45
     * @param noticeId 通知id
     * @return 受影响行
     */
    @ApiOperation(value="根据通知ID查询全部浏览人",notes="根据通知ID查询全部浏览人")
    @ResponseBody
    @RequestMapping(value = "selectAllBrowserByNoticeId/{noticeId}", method = RequestMethod.GET)
    public ItooResult selectAllBrowserByNoticeId(@PathVariable String noticeId) {
        List<PersonalInfoEntity> personalInfoEntityList;
        try {
            personalInfoEntityList = browseFacade.selectAllBrowserByNoticeId(noticeId);
            if (personalInfoEntityList != null) {
                return ItooResult.build("0000", "根据通知ID查询全部浏览人成功！",personalInfoEntityList);
            } else {
                return ItooResult.build("1111", "根据通知ID查询全部浏览人失败！");
            }
        } catch (Exception e) {
            logger.error("selectAllBrowserByNoticeId 根据通知ID查询全部浏览人异常", e);
            return ItooResult.build("1111", "根据通知ID查询全部浏览人异常！");
        }

    }


    /**
     * 根据通知ID查询全部浏览人（树形结构）-haoguiting-2017-12-5 14:15:45
     * @param noticeId 通知id
     * @return 受影响行
     */
    @ApiOperation(value="根据通知ID查询全部浏览人（树形结构）",notes="根据通知ID查询全部浏览人（树形结构）")
    @ResponseBody
    @RequestMapping(value = "selectAllBrowserByNoticeIdAsTree/{noticeId}", method = RequestMethod.GET)
    //@RequestMapping(value = "selectAllBrowserByNoticeId/{noticeId}", method = RequestMethod.POST)
    public ItooResult selectAllBrowserByNoticeIdAsTree(@PathVariable String noticeId) {
        List<TreeEntity> listTree;
        try {
            List<PersonalInfoEntity> personalEntitysByNotice = browseFacade.selectAllBrowserByNoticeId(noticeId);
            listTree = convertBrowserTreeList(personalEntitysByNotice);
            if (personalEntitysByNotice != null) {
                return ItooResult.build("0000", "根据通知ID查询全部浏览人成功！",listTree);
            } else {
                return ItooResult.build("1111", "根据通知ID查询全部浏览人失败！");
            }
        } catch (Exception e) {
            logger.error("selectAllBrowserByNoticeId 根据通知ID查询全部浏览人异常", e);
            return ItooResult.build("1111", "根据通知ID查询全部浏览人异常！");
        }

    }

    /**
     * 查询全部接受人员（树形结构），并标记好已选择的接收人 haoguiting -2018年1月14日
     * @param personalEntitysByNotice 某通知下的接收人list
     * @return 树形结构list
     */
    public List<TreeEntity> convertBrowserTreeList(List<PersonalInfoEntity> personalEntitysByNotice) {
        List<TreeEntity> listTree = new ArrayList<>();   // Tree实体集合
        List<PersonGradeModel> PersonGradeModelList = browseFacade.selectAllBrowsersIncludeGradeName();  //查询全部接受人信息
        //将期数加入到树中
        List<PeriodPersonModel> periodPersonModelList=browseFacade.findPeriodPersonModels();
        for(PeriodPersonModel periodPersonModel:periodPersonModelList){
            TreeEntity tree = new TreeEntity();
            tree.setId(periodPersonModel.getPeriodId());// 树节点Id   peopleId
            tree.setName(periodPersonModel.getPeriodName());// 树的节点名称 peopleName
            listTree.add(tree);
        }
        //将学生加入到树中
        for (PersonGradeModel  PersonGradeModel: PersonGradeModelList) {
            TreeEntity tree = new TreeEntity();
            tree.setId(PersonGradeModel.getId());// 树节点Id   peopleId
            tree.setpId(PersonGradeModel.getGrade());// 树的父节点Id  期数
            tree.setName(PersonGradeModel.getName());// 树的节点名称 peopleName
            tree.setOpen(false);       //默认树形结构是折叠形状
            //tree.getpId() 如果pid存在，去查对应的期数是哪个，并标记为checkout
            if (("").equals(PersonGradeModel.getGrade())) {
                tree.setOpen(true);
            }
            if (!personalEntitysByNotice.isEmpty()) {
                for (PersonalInfoEntity personalEntityByNotice : personalEntitysByNotice) {
                    if ((PersonGradeModel.getId()).equals(personalEntityByNotice.getId())) {
                        tree.setChecked(true);
                        tree.setOpen(true);
                        //判断其pid对应的id，使checked为true
                        for (TreeEntity oneTree : listTree) {
                            if ((PersonGradeModel.getGrade()).equals(oneTree.getId())) {
                                oneTree.setChecked(true);
                                oneTree.setOpen(true);
                                break;
                            }
                        }
                        break;
                    }
                }
            }
            listTree.add(tree);
        }


        return listTree;
   }


//    /**
//     * 查询全部期数（构建树形结构）--hgt-2018-1-30
//     */
//    public ItooResult selectAllGrade(){
//        List<DictionaryEntity> dictionaryEntityList;
//        try{
//            dictionaryEntityList=browseFacade.selectAllGrade();
//            if (dictionaryEntityList != null) {
//                return ItooResult.build("0000", "查询全部期数成功！",dictionaryEntityList);
//            } else {
//                return ItooResult.build("1111", "查询全部期数失败！");
//            }
//        } catch (Exception e) {
//            logger.error("selectAllBrowserByNoticeId 查询全部期数异常", e);
//            return ItooResult.build("1111", "查询全部期数异常！");
//        }
//    }

    /**
     * 条件查询（根据姓名查询浏览人，定位树形结构）-haoguiting-2018-2-1
     * @param name 姓名
     * @param noticeId  通知id
     * @return flag是否存在此人
     */
    @ApiOperation(value="条件查询浏览人",notes="条件查询浏览人")
    @ResponseBody
    @RequestMapping(value = "selectBrowserByCombination/{name}/{noticeId}",method = RequestMethod.GET)
    public ItooResult selectBrowserByCombination(@PathVariable String name,@PathVariable String noticeId){
        List<TreeEntity> listTree;   // Tree实体集合@PathVariable String noticeId
        boolean flag=false;
        try{
            listTree=selectAllBrowserByNoticeIdTree(noticeId);
            if (!listTree.isEmpty()) {
                for (TreeEntity tree : listTree) {
                    if ((tree.getName()).equals(name)) {
                        tree.setChecked(true); //条件查询后刷新树结构
                        tree.setOpen(true);
                        flag=true;
                        //判断其pid对应的id，使checked为true
                        for (TreeEntity oneTree : listTree) {
                            if ((tree.getpId()).equals(oneTree.getId())) {
                                oneTree.setChecked(true);
                                oneTree.setOpen(true);
                                break;
                            }
                        }
                        break;
                    }
                }
                if (flag){
                    return ItooResult.build("0000", "条件查询浏览人成功！",listTree);
                }else{
                    return ItooResult.build("0000", "没有查询到此人",listTree);
                }

            } else {
                return ItooResult.build("1111", "条件查询浏览人失败！");
            }
        }catch (Exception e){
            logger.error("selectBrowserByCombination 条件查询浏览人异常", e);
            return ItooResult.build("1111", "条件查询浏览人异常！");
        }
    }

    /**
     * 根据通知ID查询全部浏览人（条件查询）-haoguiting-2017-12-5 14:15:45
     * @param noticeId 通知id
     * @return 树形结构list
     */
    @ApiOperation(value="根据通知ID查询全部浏览人（条件查询）",notes="根据通知ID查询全部浏览人（条件查询）")
    @ResponseBody
    @RequestMapping(value = "selectAllBrowserByNoticeIdTree/{noticeId}", method = RequestMethod.GET)
    public List<TreeEntity> selectAllBrowserByNoticeIdTree(@PathVariable String noticeId) {
        List<TreeEntity> listTree;
        List<PersonalInfoEntity> personalEntitysByNotice = browseFacade.selectAllBrowserByNoticeId(noticeId);
        listTree = convertBrowserTreeList(personalEntitysByNotice);
        return listTree;

    }

}

